<template>
    <!-- 折线图 -->
    <div ref="chartRef" class="w-100 h-100"></div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import * as echarts from "echarts";
import { useSysStore } from "../../store";
import * as _ from "lodash";

const { xField, yFields, colors } = defineProps({
    xField: { type: String },
    yFields: { type: Array },
    colors: { type: Array },
});
const chartRef = ref();
const sysStore = useSysStore();
const options = reactive({
    tooltip: {
        trigger: "axis",
    },
    legend: {
        data: [],
    },
    grid: {
        left: "20px",
        right: "30px",
        bottom: "20px",
        containLabel: true,
    },
    xAxis: {
        type: "category",
        boundaryGap: true,
        data: [],
    },
    yAxis: {
        type: "value",
    },
    series: [],
});
let chart;
let observer = new ResizeObserver(() => {
    chart && chart.resize();
});

onMounted(() => {
    let userConfig = sysStore.getUserConfig();
    let theme = userConfig.theme;
    let echartsTheme = "light";
    if (theme == "dark") {
        echartsTheme = "dark";
    }
    chart = echarts.init(chartRef.value, echartsTheme);
    observer.observe(chartRef.value);
});

function reload(data, config = {}) {
    if (!data) {
        return;
    }

    let xarr = [];
    let yarr = [];
    let legend = [];
    let allLine = true;

    if (_.isArray(data)) {
        // 数据是列表类型的数据
        data.forEach((item) => {
            xarr.push(item[xField]);
        });

        yFields.forEach((yField) => {
            let arr = [];
            data.forEach((item) => {
                arr.push(item[yField.prop]);
            });

            yarr.push({
                ...yField,
                data: arr,
            });

            if (yField.type == "bar") {
                allLine = false;
            }
            legend.push(yField.name);
        });
    } else {
        //  数据是map类型的数据
        for (var name in data) {
            const list = data[name];
            if (!list?.length) {
                return;
            }

            // 初始化x轴
            if (!xarr.length) {
                list.forEach((item) => xarr.push(item[xField]));
            }

            // 数据处理
            let arr = [];
            list.forEach((item) => {
                arr.push(item[config.prop]);
            });

            let type = config.type || "bar";
            if (type == "bar") {
                allLine = false;
            }
            yarr.push({
                name,
                ...config,
                data: arr,
            });
            legend.push(name);
        }
    }

    if (allLine) {
        options.xAxis.boundaryGap = false;
    }

    options.xAxis.data = xarr;
    options.series = yarr;
    options.color = colors;
    options.legend.data = legend;

    options.backgroundColor = "";
    chart.setOption(options);
}

defineExpose({
    reload,
});
</script>

<style lang="scss" scoped></style>
